//
//  WSAuthorViewController.m
//  GroupFourFM
//
//  Created by dllo on 15/12/23.
//  Copyright © 2015年 GroupFour. All rights reserved.
//

#import "WSAuthorViewController.h"
#import "WSResource.h"
#import "WSAuthorSectionModel.h"
#import "WSAuthorItem.h"
#import "WSSectionView.h"
#import "WHAuthorDetailViewController.h"
#import "WSAuthorMoreViewController.h"
#import "WSBmob.h"
#import <WSProgressHUD.h>
#import "WSAuthorReusableView.h"
#import "WSLoginViewController.h"

@interface WSAuthorViewController ()<UICollectionViewDataSource,  UICollectionViewDelegate, WSSectionViewDelegate, WSAuthorItemDelegate, WSAuthorReusableViewDelegate>{

    WSProgressHUD *hud;
}

@property (nonatomic, strong) UICollectionView *tableView;
@property (nonatomic, strong) NSMutableArray *sectionArray;
@property (nonatomic, strong) NSMutableArray *authorArray;
@property (nonatomic, assign) NSInteger currentPage;

@end

@implementation WSAuthorViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.sectionArray = [NSMutableArray array];
    self.authorArray = [NSMutableArray array];
    [self createTableView];
    [self getData];
    self.currentPage = 1;
    
    hud = [[WSProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:hud];
}

#pragma mark - 创建tableView
- (void)createTableView {
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.sectionInset = UIEdgeInsetsMake(7, 15, 10, 15);
    flowLayout.minimumLineSpacing = 15;
    flowLayout.headerReferenceSize = CGSizeMake(SCREEN_WIDTH, 40);
    flowLayout.itemSize = CGSizeMake((SCREEN_WIDTH - 60) / 3, SCREEN_WIDTH * 0.5 - 17);
    
    self.tableView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) collectionViewLayout:flowLayout];
    [self.view addSubview:self.tableView];
    self.tableView.backgroundColor = WHITE;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.tableView registerClass:[WSAuthorItem class]  forCellWithReuseIdentifier:@"authorTableCell"];
    [self.tableView registerClass:[WSAuthorReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"authorHeader"];
    [self.tableView reloadData];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.equalTo(self.view);
    }];
    
#pragma mark - 下拉加载
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(getData)];
    self.tableView.mj_footer = footer;
    
}

#pragma mark - tableView delegate && dataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {

    return self.sectionArray.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    return 3;
}

#pragma mark 设置cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    WSAuthorItem *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"authorTableCell" forIndexPath:indexPath];
    cell.delegate = self;
    cell.authorModel = [[self.authorArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {

    WSAuthorReusableView *reusableView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"authorHeader" forIndexPath:indexPath];
    
    reusableView.delegate = self;
    reusableView.title = ((WSAuthorSectionModel *)[self.sectionArray objectAtIndex:indexPath.section]).title;
    
    return reusableView;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {

    WSAuthorModel *model = [[self.authorArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    WHAuthorDetailViewController *authorDetailVC = [[WHAuthorDetailViewController alloc] init];
    [(WSTabBarController *)self.tabBarController isHiddenTabBar:YES withViewController:authorDetailVC];
    authorDetailVC.uid = model.uid;
    authorDetailVC.myTitle = model.nickname;
    [self.navigationController pushViewController:authorDetailVC animated:YES];
}

#pragma mark - 数据请求
-(void)getData {
    
    NSString *urlStr = [NSString stringWithFormat:@"http://mobile.ximalaya.com/m/explore_user_index?device=iphone&page=%ld",self.currentPage];
    
    [WSResource getDataWithURL:urlStr block:^(id result) {
        
        [[WSBmob shareBmob] selectRelationWithUid:[[NSUserDefaults standardUserDefaults] objectForKey:@"uId"] tableName:@"Collect_author" block:^(id results) {
            
            NSMutableArray *listArray = [result objectForKey:@"list"];
            NSMutableArray *selectArr = results;
            for (NSDictionary *sectionDic in listArray) {
                
                WSAuthorSectionModel *model = [[WSAuthorSectionModel alloc] init];
                model.resluts = selectArr;
                [model setValuesForKeysWithDictionary:sectionDic];
                [self.sectionArray addObject:model];
                [self.authorArray addObject:model.list];
            }
            
            self.currentPage++;
            [self.tableView.mj_footer endRefreshing];
            [self.tableView reloadData];
            
        }];
        
    } error:^(NSError *error) {
        
        
    }];
}

#pragma mark - 实现协议方法,跳转到详情页面
-(void)JumpToAuthorView:(NSInteger)userId :(NSString *)myTitle
{
    
    WHAuthorDetailViewController *authorDetailVC = [[WHAuthorDetailViewController alloc] init];
    
    //TONavigationBarController *naVC = [[TONavigationBarController alloc] initWithRootViewController:authorDetailVC];
    [(WSTabBarController *)self.tabBarController isHiddenTabBar:YES withViewController:authorDetailVC];
    authorDetailVC.uid = userId;
    authorDetailVC.myTitle = myTitle;
    [self.navigationController pushViewController:authorDetailVC animated:YES];
    
}

#pragma mark - 实现协议方法,跳转到更多详情页面
-(void)pushMoreViewControllerWithTitle:(NSString *)title num:(NSInteger)num{
    
    WSAuthorMoreViewController *moreVC = [[WSAuthorMoreViewController alloc] init];
    WSAuthorSectionModel *model = [self.sectionArray objectAtIndex:num];
    moreVC.authorName = model.name;
    moreVC.authorTitle = model.title;
    [self.navigationController pushViewController:moreVC animated:YES];
}

- (void)collectedWithModel:(WSAuthorModel *)model {
    
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"isLogin"] isEqualToString:@"1"]) {
        
        if (model.objectId != nil) {
            
            [self alertViewControllerWithTitle:@"取消关注？" content:nil block:^{
                
                [hud showWithString:nil];
                [[WSBmob shareBmob] deleteRelationWithObjectId:model.objectId tableName:@"Collect_author" block:^(id results) {
                    
                    if ([results isEqualToString:@"successful"]) {
                        
                        model.objectId = nil;
                    }
                    [self.tableView reloadData];
                    [hud dismiss];
                }];
            }];
        }
        else {
            
            [hud showWithString:nil];
            [[WSBmob shareBmob] collectAuthorWithAuthorId:model.uid title:model.nickname content:model.personDescribe image:model.smallLogo block:^(id result) {
                
                if ([result isEqualToString:@"fail"] || result == nil) {
                    
                    [self alertViewControllerWithTitle:@"提示" content:@"关注失败"];
                }
                else {
                    
                    model.objectId = result;
                }
                [self.tableView reloadData];
                [hud dismiss];
            }];
        }
    }
    else {
    
        WSLoginViewController *loginVC = [[WSLoginViewController alloc] init];
        UINavigationController *navC = [[UINavigationController alloc] initWithRootViewController:loginVC];
        navC.navigationBarHidden = YES;
        [self presentViewController:navC animated:YES completion:nil];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
